﻿using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using System.Linq;
using System.Text.RegularExpressions;
using Store.WP7.Data;
using System;
using System.Windows.Controls;
using System.Windows.Media;
using System.IO.IsolatedStorage;
using Store.WP7.Framework.Extensions;

namespace Store.BackgroundAgent
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;
        private static readonly object _lockObject = new object();

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            StoreService storeService = new StoreService();

            //récupération des tuiles secondaires
            var orderTiles = ShellTile.ActiveTiles.Where(t => t.NavigationUri.ToString().Contains("/Views/OrderDetailsPage.xaml")).ToList();
            
            //si aucune => NotifyComplete
            if (!orderTiles.Any())
            {
                NotifyComplete();
#if DEBUG
                ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
#endif
                return;
            }

            int tileToUpdateCount = orderTiles.Count;
            int updatedTile = 0;

            //on parcourt les tuiles
            foreach (var orderTile in orderTiles)
            {
                //on récupère l'état via le service distant
                int orderId = ExtractOrderId(orderTile.NavigationUri);
                storeService.GetOrderStateAsync(orderId, serviceResult =>
                {
                    if (serviceResult.Error == null)
                    {
                        int orderState = serviceResult.Result;
                        string orderStateLabel = OrderStateHelper.GetOrderStateLabel(orderState);

                        //on créé la tuile à l'aide des APIs Silverlight
                        Grid back = new Grid();
                        back.Background = new SolidColorBrush(Colors.Orange);
                        back.Width = 173;
                        back.Height = 173;

                        TextBlock textBlock = new TextBlock();
                        textBlock.FontSize = 25;
                        textBlock.TextAlignment = TextAlignment.Right;
                        textBlock.HorizontalAlignment = HorizontalAlignment.Right;
                        textBlock.VerticalAlignment = VerticalAlignment.Bottom;
                        textBlock.Margin = new Thickness(20, 10, 10, 5);
                        textBlock.Text = string.Format("{0} / 3", orderState);

                        back.Children.Add(textBlock);

                        //on sauvegarde une image dans l'isolated storage à partir du Grid
                        string imageFilePath = string.Format("Shared/ShellContent/{0}.jpg", Guid.NewGuid());

                        using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            isf.SavePictureFromUIElement(back, 173, 173, imageFilePath);
                        }

                        string imageUrl = string.Format("isostore:/{0}", imageFilePath);

                        //on met à jour la tuile
                        orderTile.Update(new StandardTileData()
                        {
                            BackBackgroundImage = new Uri(imageUrl),
                            BackContent = orderStateLabel
                        });
                    }

                    lock (_lockObject)
                    {
                        updatedTile += 1;
                        if (updatedTile == tileToUpdateCount)
                        {
                            NotifyComplete();
                            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
                        }
                    }
                });
            }
        }

        private int ExtractOrderId(System.Uri uri)
        {
            if (uri == null)
                return 0;

            return 1;
        }
    }
}